﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.Script.Serialization;
using Manager;
using Model;
using Manager.Helper;
namespace HealthSystem
{
    /// <summary>
    /// UserHandler 的摘要说明
    /// </summary>
    public class UserHandler : IHttpHandler
    {
        HW_LoginLogManager loginlogManager = new HW_LoginLogManager();
        JavaScriptSerializer ser = new JavaScriptSerializer();
        public string lockmessage = "密码已经连续错误" + (LoginCache.errortimers+1) + "次,请在" + LoginCache.expiretime + "分钟后登陆";
        public void ProcessRequest(HttpContext context)
        {
            string saction = context.Request["action"] as string;

            context.Response.ContentType = "text/plain";
            if (saction == "relogin")
            {
                Tip tip = new Tip();
                if (context.User.Identity.IsAuthenticated)
                {
                    tip.IsRight = "true";
                    tip.ErrorMessage = string.Empty;
                    context.Response.Write(ser.Serialize(tip));
                    //context.Response.End();
                    return;
                };
            }
            else
            {
                try
                {
                    Login(context);
                }
                catch (Exception ex)
                {
                    Tip tip = new Tip()
                    {
                        IsRight = "false",
                        ErrorMessage = "系统错误!",
                    };
                    context.Response.Write(ser.Serialize(tip));
                    context.Response.End();
                }
            }
           
        }
        private void Login(HttpContext context)
        {
            Tip tip = new Tip();
            string server_v1 = Convert.ToString(context.Request.ServerVariables["HTTP_REFERER"]);
            string server_v2 = Convert.ToString(context.Request.ServerVariables["SERVER_NAME"]);
            int changdu = server_v2.Length;
            if (string.IsNullOrEmpty(server_v1) || server_v1.Substring(7, changdu) != server_v2)
            {
                tip.IsRight = "false";
                tip.ErrorMessage = "非法操作！你的ip地址已经被记录";
                context.Response.Write(ser.Serialize(tip).Trim('"'));
                //context.Response.End();
                return;
            }
            
            string username = context.Request["login"].ToString();
            string password = context.Request["password"].ToString();
            password = SecrityPass.GetPassword(password);
            if (!LoginCache.iswork && LoginCache.login.ContainsKey(username))
            {
                if (LoginCache.login[username].errortimes > LoginCache.errortimers)
                {
                    tip.IsRight = "false";
                    tip.ErrorMessage = lockmessage;
                    context.Response.Write(ser.Serialize(tip).Trim('"'));
                    //context.Response.End();
                    return;
                }
            }
            HW_XXX_UserManager manager = new HW_XXX_UserManager();
            HW_XXX_User xxuser = manager.CheckUser(username);
            if (xxuser == null)
            {
                tip.IsRight = "false";
                tip.ErrorMessage = "账号或密码错误!";
                string result = ser.Serialize(tip);
                context.Response.Write(result.Trim('"'));
                //context.Response.End();
                return;
            }
            else
            {
                if (xxuser.XX_Pass != password)
                {
                    if (!LoginCache.iswork)
                    {
                        if (LoginCache.login.ContainsKey(username))
                        {
                            LoginCache.login[username].errortimes++;
                            LoginCache.login[username].lastlogintime = DateTime.Now;
                        }
                        else
                        {
                            LoginCache.login.Add(username, new LoginError { username = username, errortimes = 1, lastlogintime = DateTime.Now });
                        }
                    }
                    tip.IsRight = "false";
                    tip.ErrorMessage = "账号或密码错误!";
                    string result = ser.Serialize(tip);
                    context.Response.Write(result.Trim('"'));
                    //context.Response.End();
                    return;
                }
                else
                {
                    if (!LoginCache.iswork && LoginCache.login.ContainsKey(username))
                    {
                        LoginCache.login.Remove(username);
                    }
                    ProfileComm profile = (ProfileComm)HttpContext.Current.Profile;
                    profile.Name = xxuser.CNName;//名字
                    profile.RoleId = xxuser.RoleId.HasValue ? xxuser.RoleId.Value : 0;
                    HW_LoginLog log = new HW_LoginLog()
                    {
                        Ip = context.Request.UserHostAddress.ToString(),
                        UserName = username,
                        LoginTime = DateTime.Now,
                    };
                    if (xxuser.AdminUser != null)
                    {
                        profile.DistrictId = xxuser.AdminUser.DistrictCode;
                        profile.ParentDistrictId = xxuser.AdminUser.hW_District.ParentDistrictCode;
                        log.Name = xxuser.AdminUser.hW_Admin_Detail.WorkUnit;
                    }
                    if (xxuser.OrgUser != null)
                    {
                        //profile.RoleId = xxuser.OrgUser.RoleId.Value;
                        log.Name = xxuser.OrgUser.hw_Org.OrgName;
                    }
                    if (xxuser.SchoolUser != null)
                    {
                        //profile.RoleId = xxuser.SchoolUser.RoleId.Value;
                        log.Name = xxuser.SchoolUser.hw_School.Name;
                    }
                    profile.AdminUser = xxuser.AdminUser == null ? new HW_Manger_Admin_User() : xxuser.AdminUser;
                    profile.OrgUser = xxuser.OrgUser == null ? new HW_OrgUser() : xxuser.OrgUser;
                    profile.SchoolUser = xxuser.SchoolUser == null ? new HW_School_User() : xxuser.SchoolUser;
                    profile.Save();
                    try
                    {
                        loginlogManager.Add(log);
                    }
                    catch
                    {
                    }
                    FormsAuthenticationTicket ticket = new FormsAuthenticationTicket(1, username,DateTime.Now,DateTime.Now.AddMinutes(20),true,context.Request.UserHostAddress);
                    string authTicket = FormsAuthentication.Encrypt(ticket);
                    HttpCookie coo = new HttpCookie(FormsAuthentication.FormsCookieName, authTicket);
                    coo.Expires = DateTime.Now.AddMinutes(20);
                    context.Response.Cookies.Add(coo);
                    //FormsAuthentication.SetAuthCookie(username, true);
                    tip.IsRight = "true";
                    string result = ser.Serialize(tip);
                    context.Response.Write(result);
                    return;
                    //FormsAuthentication.RedirectFromLoginPage(username, true);
                    //context.Response.Redirect("HealthMain.aspx"); 
                    //Page.Response.Redirect("HealthMain.aspx");
                }
            }
        }
        public bool IsReusable
        {
            get
            {
                return false;
            }
        }
    }
    public class Tip
    {
        public string IsRight { get; set; }
        public string ErrorMessage { get; set; }
    }
}